//
//  MJPhotoBrowser.m
//
//  Created by mj on 13-3-4.
//  Copyright (c) 2013年 itcast. All rights reserved.

#import <QuartzCore/QuartzCore.h>
#import "MJPhotoBrowser.h"
//#import "SDWebImageManager+MJ.h"
#import "SDWebImageManager.h"
#import "MJPhotoView.h"
#import "MJPhotoToolbar.h"
#import <SDWebImage/SDWebImageDownloader.h>

@interface MJPhotoBrowser () <MJPhotoViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) MJPhotoToolbar *toolbar;
@end

@implementation MJPhotoBrowser

#pragma mark - Lifecycle

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)loadView {
    
    self.view = [[UIView alloc] init];
    self.view.frame = [UIScreen mainScreen].bounds;
	self.view.backgroundColor = [UIColor blackColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    // 1.创建UIScrollView
    [self createScrollView];
    [self setCurrentPhotoIndex:_currentPhotoIndex];
    // 2.创建工具条
    [self createToolbar];
}

- (void)show {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.view];
    self.view.alpha = 1;
    [window.rootViewController addChildViewController:self];
}

#pragma mark - 私有方法
#pragma mark 创建工具条
- (void)createToolbar
{
    CGFloat barHeight = 94 + kSCScreenBottomOffset;
    CGFloat barY = self.view.frame.size.height - barHeight;
    _toolbar = [[MJPhotoToolbar alloc] init];
    _toolbar.frame = CGRectMake(0, barY, self.view.frame.size.width, barHeight);
    _toolbar.showSaveBtn = _showSaveBtn;
    _toolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    _toolbar.photos = _photos;
    [self.view addSubview:_toolbar];
    
    [self updateTollbarState];
}

#pragma mark 创建UIScrollView
- (void)createScrollView
{
    CGRect frame = [UIScreen mainScreen].bounds;
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = frame.size;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.pagingEnabled = YES;
    [_collectionView registerClass:UICollectionViewCell.class forCellWithReuseIdentifier:@"UICollectionViewCell"];
    [self.view addSubview:_collectionView];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _photos.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionViewCell" forIndexPath:indexPath];
    if (cell.contentView.subviews.count == 0) {
        MJPhotoView *photoView = [[MJPhotoView alloc] init];
        photoView.frame = cell.bounds;
        photoView.tag = 2020;
        photoView.photoViewDelegate = self;
        [cell.contentView addSubview:photoView];
    }
    
    MJPhotoView *photoView = [cell.contentView viewWithTag:2020];
    MJPhoto *photo = _photos[indexPath.item];
    photoView.photo = photo;
    return cell;
}

- (void)setPhotos:(NSArray *)photos {
    _photos = photos;
    _toolbar.photos = _photos;
    [self.collectionView reloadData];
//    if (photos.count > 1) {
//        _visiblePhotoViews = [NSMutableSet set];
//        _reusablePhotoViews = [NSMutableSet set];
//    }
    
//    CGFloat w = _photoScrollView.frame.size.width;
//    _photoScrollView.contentSize = CGSizeMake(w * _photos.count, 0);
//
//    for (int i = 0; i<_photos.count; i++) {
//        MJPhoto *photo = _photos[i];
//        photo.index = i;
//        photo.firstShow = i == _currentPhotoIndex;
//    }
}

#pragma mark 设置选中的图片
- (void)setCurrentPhotoIndex:(NSUInteger)currentPhotoIndex
{
    _currentPhotoIndex = currentPhotoIndex;
    
    for (int i = 0; i<_photos.count; i++) {
        MJPhoto *photo = _photos[i];
        photo.firstShow = i == currentPhotoIndex;
    }
    
    if (self.isViewLoaded) {
        CGFloat w = _collectionView.frame.size.width;
        CGFloat offset = _currentPhotoIndex * w;
//        if (offset > _collectionView.contentSize.width) {
//            offset = 0;
//        }
        _collectionView.contentOffset = CGPointMake(offset, 0);
//        [self showPhotos];
    }
}

#pragma mark - MJPhotoView代理
- (void)photoViewSingleTap:(MJPhotoView *)photoView
{
//    [UIApplication sharedApplication].statusBarHidden = _statusBarHiddenInited;
    
    // 移除工具条
    [_toolbar removeFromSuperview];
    
    [UIView animateWithDuration:0.15 animations:^{
        self.view.alpha = 0;
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }];
}

- (void)photoViewDidEndZoom:(MJPhotoView *)photoView
{
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (void)photoViewImageFinishLoad:(MJPhotoView *)photoView
{
    _toolbar.currentPhotoIndex = _currentPhotoIndex;
}

#pragma mark 显示照片
/*
- (void)showPhotos
{
    // 只有一张图片
    if (_photos.count == 1) {
        [self showPhotoViewAtIndex:0];
        return;
    }
    
    CGRect visibleBounds = _photoScrollView.bounds;
	NSInteger firstIndex = (int)floorf((CGRectGetMinX(visibleBounds)+kPadding*2) / CGRectGetWidth(visibleBounds));
	NSInteger lastIndex  = (int)floorf((CGRectGetMaxX(visibleBounds)-kPadding*2-1) / CGRectGetWidth(visibleBounds));
    if (firstIndex < 0) firstIndex = 0;
    if (firstIndex >= _photos.count) firstIndex = _photos.count - 1;
    if (lastIndex < 0) lastIndex = 0;
    if (lastIndex >= _photos.count) lastIndex = _photos.count - 1;
	
	// 回收不再显示的ImageView
    NSInteger photoViewIndex;
	for (MJPhotoView *photoView in _visiblePhotoViews) {
        photoViewIndex = kPhotoViewIndex(photoView);
		if (photoViewIndex < firstIndex || photoViewIndex > lastIndex) {
			[_reusablePhotoViews addObject:photoView];
			[photoView removeFromSuperview];
		}
	}
    
	[_visiblePhotoViews minusSet:_reusablePhotoViews];
    while (_reusablePhotoViews.count > 2) {
        [_reusablePhotoViews removeObject:[_reusablePhotoViews anyObject]];
    }
	
	for (NSUInteger index = firstIndex; index <= lastIndex; index++) {
		if (![self isShowingPhotoViewAtIndex:index]) {
			[self showPhotoViewAtIndex:index];
		}
	}
}
*/

#pragma mark 显示一个图片view
//- (void)showPhotoViewAtIndex:(NSUInteger)index
//{
//    MJPhotoView *photoView = [self dequeueReusablePhotoView];
//    if (!photoView) { // 添加新的图片view
//        photoView = [[MJPhotoView alloc] init];
//        photoView.photoViewDelegate = self;
//    }
//
//    // 调整当期页的frame
//    CGRect bounds = _photoScrollView.bounds;
//    CGRect photoViewFrame = bounds;
//    photoViewFrame.size.width -= (2 * kPadding);
//    photoViewFrame.origin.x = (bounds.size.width * index) + kPadding;
//    photoView.tag = kPhotoViewTagOffset + index;
//
//    MJPhoto *photo = _photos[index];
//    photoView.frame = photoViewFrame;
//    photoView.photo = photo;
//
//    [_visiblePhotoViews addObject:photoView];
//    [_photoScrollView addSubview:photoView];
//
//    [self loadImageNearIndex:index];
//}

#pragma mark 加载index附近的图片
- (void)loadImageNearIndex:(NSUInteger)index
{
    if (index > 0) {
        MJPhoto *photo = _photos[index - 1];
        [self downloadWithURL:photo.url];
    }
    
    if (index < _photos.count - 1) {
        MJPhoto *photo = _photos[index + 1];
        [self downloadWithURL:photo.url];
    }
}

- (void)downloadWithURL:(NSURL *)url {
    // cmp不能为空
  [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url options:SDWebImageDownloaderLowPriority progress:nil completed:nil];
}


#pragma mark index这页是否正在显示
//- (BOOL)isShowingPhotoViewAtIndex:(NSUInteger)index {
//	for (MJPhotoView *photoView in _visiblePhotoViews) {
//		if (kPhotoViewIndex(photoView) == index) {
//           return YES;
//        }
//    }
//	return  NO;
//}

#pragma mark 循环利用某个view
//- (MJPhotoView *)dequeueReusablePhotoView
//{
//    MJPhotoView *photoView = [_reusablePhotoViews anyObject];
//	if (photoView) {
//		[_reusablePhotoViews removeObject:photoView];
//	}
//	return photoView;
//}

#pragma mark 更新toolbar状态
- (void)updateTollbarState
{
    
    _currentPhotoIndex = _collectionView.contentOffset.x / _collectionView.frame.size.width;
    _toolbar.currentPhotoIndex = _currentPhotoIndex;
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//	[self showPhotos];
    [self updateTollbarState];
}
@end
